const Router = require('koa-router')
const axios = require('axios')
const path = require('path')
const MemoryFs = require('memory-fs')
const webpack = require('webpack')
const VueServerRenderer = require('vue-server-renderer')
const fs = require('fs')
const serverConfig = require('../../build/webpack.config.server')

const serverComplier = webpack(serverConfig)

const serverRender = require('./server-rander')

const mfs = new MemoryFs()
serverComplier.outputFileSystem = mfs

let bundle;
serverComplier.watch({}, (err, stats) => {
    if (err) throw err
    stats = stats.toJson()
    stats.errors.forEach(err => console.info(err))
    stats.warnings.forEach(warn => console.info(warn))

    const bundlePath = path.join(
        serverConfig.output.path,
        'vue-ssr-server-bundle.json'
    )
    bundle = JSON.parse(mfs.readFileSync(bundlePath, 'utf-8'))

    console.info('新的bundle已经生成')
})

const handleSSR = async(ctx) => {
    if (bundle) {
        ctx.body = '等一会儿'
        return
    }

    const clinetMainifestResp = await axios.get(
        'http://127.0.0.1:8000/vue-ssr-client-mainifest.json'
    )

    const clinetMainifest = clinetMainifestResp.data

    const template = fs.readFileSync(path.join(__dirname, '../server-template.ejs'))

    const renderer = VueServerRenderer.createBundleRenderer(bundle, {
        inject: false,
        clinetMainifest
    })

    await serverRender(ctx, renderer, template)
}

const router = new Router()
router.get('*', handleSSR)

module.exports = router